<template>
  <div class="registration-page">
    <div class="action-buttons">
      <el-button type="primary" size="small" @click="addNewReg()">
        <el-icon><Edit/></el-icon> &nbsp;挂号
      </el-button>
      <el-button type="primary" size="small" @click="clear()">
        <el-icon><Refresh/></el-icon>&nbsp;清空
      </el-button>
    </div>

    <div class="form-title">挂号信息</div>

    <!-- 第一行：病历号、姓名、性别、年龄 -->
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">病 历 号 :</span>
          <el-input
              placeholder="输入病历号"
              style="width: 110px"
              size="small"
              v-model="formData.casenumber"
              @blur="blhcx()">
          </el-input>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>
          <el-input
              placeholder="输入姓名"
              style="width: 110px"
              size="small"
              v-model="formData.realname">
          </el-input>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>
          <el-select
              placeholder="选择性别"
              style="width: 110px"
              size="small"
              v-model="formData.gender">
            <el-option
                v-for="item in sexData"
                :key="item.id"
                :label="getDisplayLabel(item)"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="7">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄:</span>
          <el-input
              placeholder="输入年龄"
              style="width: 110px"
              size="small"
              v-model="formData.age">
          </el-input>
          <span class="required">*</span>
          <el-select
              placeholder="选择单位"
              style="width: 110px"
              size="small"
              v-model="formData.agetype">
            <el-option label="岁" value="岁"></el-option>
            <el-option label="月" value="月"></el-option>
            <el-option label="天" value="天"></el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行：出生日期、身份证号、家庭住址 -->
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="form-item">
          <span class="label">出生日期:</span>
          <el-date-picker
              @change="calculateAge"
              v-model="formData.birthdate"
              type="date"
              placeholder="出生日期"
              size="small"
              style="width: 124px"
              value-format="YYYY-MM-DD">
          </el-date-picker>
        </div>
      </el-col>

      <el-col :span="7">
        <div class="form-item">
          <span class="label">身份证号:</span>
          <el-input
              placeholder="在此输入身份证号"
              style="width: 230px"
              size="small"
              v-model="formData.idnumber"></el-input>
        </div>
      </el-col>

      <el-col :span="7">
        <div class="form-item">
          <span class="label">家庭住址:</span>
          <el-input
              placeholder="在此输入家庭住址"
              style="width: 250px"
              size="small"
              v-model="formData.homeaddress">
          </el-input>
        </div>
      </el-col>
    </el-row>

    <!-- 第三行：结算类别、看诊日期、午别、挂号科室 -->
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">结算类别:</span>
          <el-select
              placeholder="结算类别"
              style="width: 100px"
              size="small"
              v-model="formData.settleid">
            <el-option
                v-for="item in categories4"
                :key="item.id"
                :label="getDisplayLabel(item)"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="5">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">看诊日期:</span>
          <el-date-picker
              v-model="formData.visitdate"
              type="date"
              placeholder="看诊日期"
              size="small"
              style="width: 125px"
              value-format="YYYY-MM-DD"
              @change="kzrq_select()">
          </el-date-picker>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">午别:</span>
          <el-select
              placeholder="午别"
              style="width: 90px"
              size="small"
              v-model="formData.noon"
              @change="Noon_select()">
            <el-option
                v-for="item in categories5"
                :key="item.noon"
                :label="item.noon"
                :value="item.noon">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">挂号科室:</span>
          <el-select
              placeholder="挂号科室"
              style="width: 108px"
              size="small"
              v-model="formData.deptid"
              @change="Dept_select()">
            <el-option
                v-for="item in deptData"
                :key="item.id"
                :label="getDisplayLabel(item, 'deptname')"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <!-- 第四行：号别、看诊医生 -->
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">号&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>
          <el-select
              placeholder="号别"
              style="width: 100px"
              size="small"
              v-model="formData.registleid"
              @change="RegistLe_select()">
            <el-option
                v-for="item in categories6"
                :key="item.id"
                :label="getDisplayLabel(item)"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">看诊医生:</span>
          <el-select
              placeholder="看诊医生"
              style="width: 110px"
              size="small"
              v-model="formData.userid"
              @change="user_select()">
            <el-option
                v-for="item in doctorData"
                :key="item.id"
                :label="getDisplayLabel(item, 'realname')"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <!-- 第五行：病历本、应收金额、收费方式 -->
    <el-row :gutter="2">
      <el-col :span="4">
        <div class="form-item">
          <span class="label">病历本</span>
          <input
              type="checkbox"
              v-model="formData.isbook"
              true-value="是"
              false-value="否"
              @change="book_select()"
          />
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">应收金额:</span>
          <el-input
              placeholder="应收金额"
              style="width: 100px"
              size="small"
              v-model="formData.fee"
              readonly>
          </el-input>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="form-item">
          <span class="required">*</span>
          <span class="label">治疗方式:</span>
          <el-select
              placeholder="收费方式"
              style="width: 100px"
              size="small"
              v-model="formData.feetype">
            <el-option
                v-for="item in categories3"
                :key="item.id"
                :label="getDisplayLabel(item)"
                :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>

    <!-- 加载中遮罩 -->
    <el-loading v-model="loading" text="正在处理..."></el-loading>

    <!-- 消息提示 -->
    <el-message :message="message" :type="messageType" :duration="3000" v-if="message"></el-message>
  </div>
</template>

<script setup>
import {onMounted, ref, reactive, watch} from 'vue'
import service from '@/utils/request'
import { useCounterStore } from "@/stores/counter.js";
import { ElMessage, ElLoading } from 'element-plus';

// 状态管理
const counter = useCounterStore();
const loading = ref(false);
const message = ref('');
const messageType = ref('success');
const formLoaded = ref(false); // 表单数据是否加载完成

// 表单数据
const formData = reactive({
  casenumber: '',
  realname: '',
  gender: null,
  age: null,
  agetype: '岁',
  birthdate: null,
  idnumber: '',
  homeaddress: '',
  settleid: null,
  visitdate: new Date(),
  noon: '上午',
  deptid: null,
  registleid: null,
  userid: null,
  isbook: '否',
  fee: 0,
  feetype: null,
  registerid: null,
});

// 数据字典
const sexData = ref([]);       // 性别数据
const deptData = ref([]);      // 科室数据
const doctorData = ref([]);    // 医生数据
const categories3 = ref([]);   // 收费方式
const categories4 = ref([]);   // 结算类别
const categories5 = ref([{noon: '上午'}, {noon: '下午'}]); // 午别
const categories6 = ref([]);   // 号别

// 数据加载状态
const dataLoading = ref({
  sex: false,
  dept: false,
  feeType: false,
  settle: false,
  regLevel: false
});

// 调试函数：记录API响应
function logApiResponse(response, apiName) {
  console.log(`[${apiName}] 原始响应:`, response);

  // 尝试解析常见的数据结构
  if (response && response.data) {
    console.log(`[${apiName}] 解析后的数据:`, response.data);
  } else if (response && Array.isArray(response)) {
    console.log(`[${apiName}] 直接是数组:`, response);
  } else {
    console.log(`[${apiName}] 未知结构:`, response);
  }
}

// 模拟数据 - 结算类别（当后端返回空时使用）
const mockSettleData = [
  { id: 1, constantname: '自费' },
  { id: 2, constantname: '医保' },
  { id: 3, constantname: '新农合' },
  { id: 4, constantname: '公费医疗' }
];

// 模拟数据 - 号别（当后端返回空时使用）
const mockRegLevelData = [
  { id: 1, constantname: '普通号', price: 21 },
  { id: 2, constantname: '专家号', price: 50 },
  { id: 3, constantname: '急诊号', price: 30 },
  { id: 4, constantname: '特需号', price: 100 }
];

// 获取显示标签（安全处理）
function getDisplayLabel(item, field = 'constantname') {
  if (!item) return '[无数据]';

  // 优先使用指定字段
  if (item[field]) return item[field];

  // 尝试其他可能的字段
  if (item.constantname) return item.constantname;
  if (item.name) return item.name;
  if (item.label) return item.label;
  if (item.deptname) return item.deptname;
  if (item.realname) return item.realname;

  // 如果都没有，显示ID或默认文本
  if (item.id) return `[ID:${item.id}]`;
  return '[数据格式异常]';
}

// 病历号查询（包含模拟逻辑）
function blhcx() {
  if (!formData.casenumber) return;

  loading.value = true;
  console.log('病历号查询请求:', formData.casenumber);

  // 临时模拟接口（开发环境使用）
  if (process.env.NODE_ENV === 'development') {
    setTimeout(() => {
      if (formData.casenumber >= 1 && formData.casenumber <= 5) {
        const patient = {
          realname: `患者${formData.casenumber}`,
          gender: formData.casenumber % 2 === 0 ? 72 : 71, // 71=男，72=女
          birthdate: `2020-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
          age: Math.floor(Math.random() * 80) + 1,
          agetype: '岁',
          idnumber: `11010119${Math.floor(Math.random() * 1000000000)}${formData.casenumber % 2 === 0 ? 'X' : Math.floor(Math.random() * 10)}`,
          homeaddress: `测试地址${formData.casenumber}号`
        };

        formData.realname = patient.realname;
        formData.gender = patient.gender;
        formData.birthdate = patient.birthdate;
        formData.age = patient.age;
        formData.agetype = patient.agetype;
        formData.idnumber = patient.idnumber;
        formData.homeaddress = patient.homeaddress;

        if (formData.birthdate) {
          calculateAge();
        }

        message.value = '患者信息已加载';
        messageType.value = 'success';
      } else if (formData.casenumber >= 6 && formData.casenumber <= 10) {
        message.value = '未找到该病历号对应的患者信息';
        messageType.value = 'warning';
      } else {
        message.value = '查询失败，请重试';
        messageType.value = 'error';
      }

      loading.value = false;
    }, 500);
    return;
  }

  // 正式环境接口请求
  service.get(`/patient/getByCaseNumber?casenumber=${formData.casenumber}`)
      .then(res => {
        logApiResponse(res, '病历号查询');

        if (res && res.success && res.data) {
          const patient = res.data;
          console.log('患者信息:', patient);

          formData.realname = patient.realname || '';
          formData.gender = patient.gender || null;
          formData.birthdate = patient.birthdate || null;
          formData.age = patient.age || null;
          formData.agetype = patient.agetype || '岁';
          formData.idnumber = patient.idnumber || '';
          formData.homeaddress = patient.homeaddress || '';

          if (formData.birthdate) {
            calculateAge();
          }

          message.value = '患者信息已加载';
          messageType.value = 'success';
        } else {
          message.value = '未找到该病历号对应的患者信息';
          messageType.value = 'warning';
        }
      })
      .catch(error => {
        console.error('病历号查询失败', error);
        message.value = '查询失败，请重试';
        messageType.value = 'error';
      })
      .finally(() => {
        loading.value = false;
      });
}

// 挂号提交（包含模拟逻辑）
function addNewReg() {
  // 表单验证
  if (!validateForm()) {
    return;
  }

  // 设置当前登录用户为挂号员
  formData.registerid = counter.vo_user.userid || '模拟用户ID';

  console.log('提交挂号信息:', formData);

  // 显示加载中
  loading.value = true;

  // 临时模拟接口（开发环境使用）
  if (process.env.NODE_ENV === 'development') {
    setTimeout(() => {
      // 模拟三种情况：
      // 1. 病历号为1-3：挂号成功
      // 2. 病历号为4-6：挂号失败（模拟业务错误）
      // 3. 其他：模拟服务器错误
      if (formData.casenumber >= 1 && formData.casenumber <= 3) {
        message.value = '挂号成功';
        messageType.value = 'success';

        // 清空表单
        clear();

        console.log('挂号成功，ID:', Math.floor(Math.random() * 1000));
      } else if (formData.casenumber >= 4 && formData.casenumber <= 6) {
        message.value = '挂号失败：该患者今日已挂号';
        messageType.value = 'error';
      } else {
        message.value = '挂号失败：服务器异常（模拟500错误）';
        messageType.value = 'error';
      }

      loading.value = false;
    }, 800);
    return;
  }

  // 正式环境接口请求
  service.post("/register/add", formData)
      .then(res => {
        logApiResponse(res, '挂号提交');

        if (res && res.success) {
          message.value = '挂号成功';
          messageType.value = 'success';
          clear();
        } else {
          message.value = (res && res.message) || '挂号失败';
          messageType.value = 'error';
        }
      })
      .catch(error => {
        console.error('挂号失败', error);
        message.value = '挂号失败，请重试';
        messageType.value = 'error';
      })
      .finally(() => {
        loading.value = false;
      });
}

// 表单验证
function validateForm() {
  let isValid = true;

  // 验证必填字段
  const requiredFields = [
    { field: 'casenumber', message: '请输入病历号' },
    { field: 'realname', message: '请输入姓名' },
    { field: 'gender', message: '请选择性别' },
    { field: 'age', message: '请输入年龄' },
    { field: 'settleid', message: '请选择结算类别' },
    { field: 'visitdate', message: '请选择看诊日期' },
    { field: 'deptid', message: '请选择挂号科室' },
    { field: 'registleid', message: '请选择号别' },
    { field: 'userid', message: '请选择看诊医生' },
    { field: 'feetype', message: '请选择收费方式' }
  ];

  for (const field of requiredFields) {
    if (!formData[field.field]) {
      message.value = field.message;
      messageType.value = 'warning';
      isValid = false;
      break;
    }
  }

  // 验证年龄是否为数字
  if (isValid && formData.age && isNaN(Number(formData.age))) {
    message.value = '年龄必须为数字';
    messageType.value = 'warning';
    isValid = false;
  }

  // 验证身份证号格式（简单验证）
  if (isValid && formData.idnumber && !/^\d{15}(\d{2}[0-9Xx])?$/.test(formData.idnumber)) {
    message.value = '身份证号格式不正确';
    messageType.value = 'warning';
    isValid = false;
  }

  return isValid;
}

// 科室选择事件
function Dept_select() {
  if (!formData.deptid) {
    doctorData.value = [];
    return;
  }

  loading.value = true;
  console.log('获取医生列表，科室ID:', formData.deptid);

  service.get(`/user/getbydeptid?deptid=${formData.deptid}`)
      .then(res => {
        logApiResponse(res, '医生列表');

        if (res && Array.isArray(res)) {
          const doctors = res.filter(user => user.usetype === 3);
          console.log('过滤后的医生列表:', doctors);

          if (doctors.length > 0) {
            doctorData.value = doctors;
          } else {
            doctorData.value = [];
            message.value = '该科室暂无医生信息';
            messageType.value = 'warning';
          }
        } else if (res && res.data && Array.isArray(res.data)) {
          const doctors = res.data.filter(user => user.usetype === 3);
          console.log('过滤后的医生列表:', doctors);

          if (doctors.length > 0) {
            doctorData.value = doctors;
          } else {
            doctorData.value = [];
            message.value = '该科室暂无医生信息';
            messageType.value = 'warning';
          }
        } else {
          doctorData.value = [];
          message.value = '获取医生列表失败';
          messageType.value = 'warning';
        }
      })
      .catch(error => {
        console.error('获取医生列表失败', error);
        doctorData.value = [];
        message.value = '获取医生列表失败，请重试';
        messageType.value = 'error';
      })
      .finally(() => {
        loading.value = false;
      });
}

// 号别选择事件 - 更新应收金额
function RegistLe_select() {
  if (!formData.registleid) {
    formData.fee = 0;
    return;
  }

  // 从号别数据中获取对应的价格
  const registLevel = categories6.value.find(item => item.id === formData.registleid);

  if (registLevel && registLevel.price) {
    formData.fee = registLevel.price;
    console.log('更新应收金额为:', formData.fee);
  } else if (registLevel && registLevel.fee) {
    // 兼容可能的fee字段
    formData.fee = registLevel.fee;
    console.log('更新应收金额为:', formData.fee);
  } else {
    // 默认价格
    formData.fee = 21;
    console.log('未找到号别价格，使用默认值:', formData.fee);
  }
}

// 计算年龄
function calculateAge() {
  if (!formData.birthdate) return;

  const birthdate = new Date(formData.birthdate);
  const today = new Date();

  // 计算时间差（毫秒）
  const timeDiff = today - birthdate;
  // 计算天数
  const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
  // 计算月数（近似值）
  const monthsDiff = Math.floor(daysDiff / 30.44);
  // 计算年数
  let yearsDiff = today.getFullYear() - birthdate.getFullYear();
  // 调整年数（如果今年生日还没到）
  const monthCheck = today.getMonth() - birthdate.getMonth();

  if (monthCheck < 0 || (monthCheck === 0 && today.getDate() < birthdate.getDate())) {
    yearsDiff--;
  }

  // 确定显示类型（岁/月/天）
  let ageValue, ageType;

  if (yearsDiff >= 2) {
    ageValue = yearsDiff;
    ageType = '岁';
  } else if (monthsDiff >= 1) {
    ageValue = monthsDiff;
    ageType = '月';
  } else {
    ageValue = daysDiff;
    ageType = '天';
  }

  // 更新显示
  formData.age = ageValue;
  formData.agetype = ageType;
  console.log(`计算年龄: ${ageValue}${ageType}`);
}

// 清空表单
function clear() {
  // 保留当前用户信息
  const currentUserId = formData.registerid;

  // 重置表单数据
  Object.assign(formData, {
    casenumber: '',
    realname: '',
    gender: null,
    age: null,
    agetype: '岁',
    birthdate: null,
    idnumber: '',
    homeaddress: '',
    settleid: categories4.value.length > 0 ? categories4.value[0].id : mockSettleData[0].id,
    visitdate: new Date(),
    noon: '上午',
    deptid: null,
    registleid: categories6.value.length > 0 ? categories6.value[0].id : mockRegLevelData[0].id,
    userid: null,
    isbook: '否',
    fee: categories6.value.length > 0 ? (categories6.value[0].price || categories6.value[0].fee || 21) : 21,
    feetype: categories3.value.length > 0 ? categories3.value[0].id : null,
    registerid: currentUserId,
  });

  // 清空医生列表
  doctorData.value = [];
  console.log('表单已清空');
}

// 看诊日期选择事件
function kzrq_select() {
  console.log('看诊日期已选择:', formData.visitdate);
  // 可以添加日期相关的逻辑，例如判断是否为工作日等
}

// 午别选择事件
function Noon_select() {
  console.log('午别已选择:', formData.noon);
  // 可以添加午别相关的逻辑
}

// 医生选择事件
function user_select() {
  console.log('看诊医生已选择:', formData.userid);
  // 可以添加医生相关的逻辑，例如显示医生简介等
}

// 病历本选择事件
function book_select() {
  console.log('病历本选项已更改:', formData.isbook);
  // 可以添加病历本相关的逻辑，例如更新费用等
}

// 加载性别数据
function loadSexData() {
  dataLoading.value.sex = true;
  return service.get("/constantitem/getbytypeid2?id=7")
      .then(res => {
        logApiResponse(res, '性别数据');

        // 检查响应结构
        if (res && Array.isArray(res)) {
          sexData.value = res.map(item => ({
            ...item,
            constantname: item.constantname || item.name || `性别${item.id}`
          }));
          console.log('性别数据加载成功，数量:', res.length);
        } else if (res && res.data && Array.isArray(res.data)) {
          sexData.value = res.data.map(item => ({
            ...item,
            constantname: item.constantname || item.name || `性别${item.id}`
          }));
          console.log('性别数据加载成功，数量:', res.data.length);
        } else if (res && res.success === false) {
          console.error('性别数据请求失败:', res.message);
          sexData.value = [];
        } else {
          console.error('性别数据格式不符合预期:', res);
          sexData.value = [];
        }
      })
      .catch(error => {
        console.error('加载性别数据失败', error);
        sexData.value = [];
      })
      .finally(() => {
        dataLoading.value.sex = false;
      });
}

// 加载科室数据
function loadDeptData() {
  dataLoading.value.dept = true;
  return service.get("/dept/list")
      .then(res => {
        logApiResponse(res, '科室数据');

        // 检查响应结构
        if (res && Array.isArray(res)) {
          deptData.value = res.map(item => ({
            ...item,
            deptname: item.deptname || item.name || `科室${item.id}`
          }));
          console.log('科室数据加载成功，数量:', res.length);
        } else if (res && res.data && Array.isArray(res.data)) {
          deptData.value = res.data.map(item => ({
            ...item,
            deptname: item.deptname || item.name || `科室${item.id}`
          }));
          console.log('科室数据加载成功，数量:', res.data.length);
        } else if (res && res.success === false) {
          console.error('科室数据请求失败:', res.message);
          deptData.value = [];
        } else {
          console.error('科室数据格式不符合预期:', res);
          deptData.value = [];
        }
      })
      .catch(error => {
        console.error('加载科室数据失败', error);
        deptData.value = [];
      })
      .finally(() => {
        dataLoading.value.dept = false;
      });
}

// 加载收费方式
function loadFeeTypeData() {
  dataLoading.value.feeType = true;
  return service.get("/constantitem/getbytypeid2?id=11")
      .then(res => {
        logApiResponse(res, '收费方式');

        // 检查响应结构
        if (res && Array.isArray(res)) {
          categories3.value = res.map(item => ({
            ...item,
            constantname: item.constantname || item.name || `收费方式${item.id}`
          }));
          console.log('收费方式加载成功，数量:', res.length);
        } else if (res && res.data && Array.isArray(res.data)) {
          categories3.value = res.data.map(item => ({
            ...item,
            constantname: item.constantname || item.name || `收费方式${item.id}`
          }));
          console.log('收费方式加载成功，数量:', res.data.length);
        } else if (res && res.success === false) {
          console.error('收费方式请求失败:', res.message);
          categories3.value = [];
        } else {
          console.error('收费方式格式不符合预期:', res);
          categories3.value = [];
        }
      })
      .catch(error => {
        console.error('加载收费方式失败', error);
        categories3.value = [];
      })
      .finally(() => {
        dataLoading.value.feeType = false;
      });
}

// 加载结算类别
function loadSettleData() {
  dataLoading.value.settle = true;
  return service.get("/constantitem/getbytypeid2?id=12")
      .then(res => {
        logApiResponse(res, '结算类别');

        // 检查响应结构
        if (res && res.data && Array.isArray(res.data)) {
          if (res.data.length > 0) {
            categories4.value = res.data.map(item => ({
              ...item,
              constantname: item.constantname || item.name || `结算类别${item.id}`
            }));
            console.log('结算类别加载成功，数量:', res.data.length);
          } else {
            // 使用模拟数据
            categories4.value = mockSettleData;
            console.log('结算类别数据为空，使用模拟数据');
          }
        } else {
          // 使用模拟数据
          categories4.value = mockSettleData;
          console.log('结算类别数据格式异常，使用模拟数据');
        }
      })
      .catch(error => {
        console.error('加载结算类别失败', error);
        categories4.value = mockSettleData;
        console.log('加载结算类别失败，使用模拟数据');
      })
      .finally(() => {
        dataLoading.value.settle = false;
      });
}

// 加载号别
function loadRegLevelData() {
  dataLoading.value.regLevel = true;
  return service.get("/constantitem/getbytypeid2?id=13")
      .then(res => {
        logApiResponse(res, '号别数据');

        // 检查响应结构
        if (res && res.data && Array.isArray(res.data)) {
          if (res.data.length > 0) {
            categories6.value = res.data.map(item => ({
              ...item,
              constantname: item.constantname || item.name || `号别${item.id}`,
              price: item.price || item.fee || 21
            }));
            console.log('号别加载成功，数量:', res.data.length);
          } else {
            // 使用模拟数据
            categories6.value = mockRegLevelData;
            console.log('号别数据为空，使用模拟数据');
          }
        } else {
          // 使用模拟数据
          categories6.value = mockRegLevelData;
          console.log('号别数据格式异常，使用模拟数据');
        }
      })
      .catch(error => {
        console.error('加载号别失败', error);
        categories6.value = mockRegLevelData;
        console.log('加载号别失败，使用模拟数据');
      })
      .finally(() => {
        dataLoading.value.regLevel = false;
      });
}

// 页面加载初始化
onMounted(() => {
  console.log('页面初始化，开始加载数据字典...');

  // 加载数据字典
  Promise.all([
    loadSexData(),
    loadDeptData(),
    loadFeeTypeData(),
    loadSettleData(),
    loadRegLevelData()
  ])
      .then(() => {
        console.log('所有数据字典加载完成');
        console.log('数据状态:', {
          sex: sexData.value.length,
          dept: deptData.value.length,
          feeType: categories3.value.length,
          settle: categories4.value.length,
          regLevel: categories6.value.length
        });

        formLoaded.value = true;

        // 设置默认值
        setDefaultValues();

        // 检查是否所有数据都加载成功
        const allDataLoaded =
            sexData.value.length > 0 &&
            deptData.value.length > 0 &&
            categories3.value.length > 0 &&
            categories4.value.length > 0 &&
            categories6.value.length > 0;

        if (allDataLoaded) {
          message.value = '数据加载成功';
          messageType.value = 'success';
        } else {
          message.value = '部分数据使用默认值，请联系管理员';
          messageType.value = 'warning';
        }
      })
      .catch(error => {
        console.error('初始化数据加载失败', error);
        message.value = '数据加载失败，请刷新页面';
        messageType.value = 'error';
      });
});

// 设置表单默认值
function setDefaultValues() {
  console.log('设置表单默认值...');

  // 设置当前用户为挂号员
  if (counter.vo_user && counter.vo_user.userid) {
    formData.registerid = counter.vo_user.userid;
    console.log('设置挂号员为:', formData.registerid);
  }

  // 设置默认号别和费用
  if (categories6.value.length > 0) {
    const defaultRegLevel = categories6.value[0];
    formData.registleid = defaultRegLevel.id;
    formData.fee = defaultRegLevel.price || defaultRegLevel.fee || 21;
    console.log('设置默认号别:', getDisplayLabel(defaultRegLevel), '费用:', formData.fee);
  } else {
    console.warn('号别数据为空，使用模拟默认值');
    formData.registleid = mockRegLevelData[0].id;
    formData.fee = mockRegLevelData[0].price;
    console.log('设置默认号别:', mockRegLevelData[0].constantname, '费用:', formData.fee);
  }

  // 设置默认结算类别
  if (categories4.value.length > 0) {
    const defaultSettle = categories4.value[0];
    formData.settleid = defaultSettle.id;
    console.log('设置默认结算类别:', getDisplayLabel(defaultSettle));
  } else {
    console.warn('结算类别数据为空，使用模拟默认值');
    formData.settleid = mockSettleData[0].id;
    console.log('设置默认结算类别:', mockSettleData[0].constantname);
  }

  // 设置默认收费方式
  if (categories3.value.length > 0) {
    formData.feetype = categories3.value[0].id;
    console.log('设置默认收费方式:', getDisplayLabel(categories3.value[0]));
  } else {
    console.warn('收费方式数据为空，无法设置默认值');
  }

  // 设置默认看诊日期为今天
  formData.visitdate = new Date();
  console.log('设置默认看诊日期:', formData.visitdate);

  console.log('表单默认值设置完成');
}

// 监听表单数据变化（用于调试）
watch(formData, (newVal, oldVal) => {
  console.log('表单数据变化:', newVal);
}, { deep: true });
</script>

<style scoped>
.registration-page {
  padding: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
}

.action-buttons {
  margin-bottom: 20px;
}

.form-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  font-size: 13px;
  width: 80px;
  text-align: right;
  margin-right: 5px;
}

.required {
  color: red;
  margin-right: 2px;
}

/* 表单行间距优化 */
.el-row {
  margin-bottom: 10px;
}

/* 输入框样式 */
.el-input {
  width: 100%;
}

/* 下拉框样式 */
.el-select {
  width: 100%;
}

/* 按钮组样式 */
.action-buttons {
  display: flex;
  gap: 10px;
}

/* 响应式布局 - 小屏幕适配 */
@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 10px;
  }

  .label {
    width: 60px;
  }
}
</style>